#define _CRT_SECURE_NO_WARNINGS 1

//https://leetcode.cn/problems/nearest-exit-from-entrance-in-maze/

class Solution {
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
    int m, n;

public:
    int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {
        int m = maze.size(), n = maze[0].size();
        bool vis[m][n];
        memset(vis, 0, sizeof(vis));
        vis[entrance[0]][entrance[1]] = true;
        queue<pair<int, int>> q;
        q.push({ entrance[0],entrance[1] });
        int step = 0;
        while (q.size())
        {
            step++;
            int sz = q.size();
            for (int i = 0; i < sz; i++)
            {
                auto [a, b] = q.front();
                q.pop();
                for (int z = 0; z < 4; z++)
                {
                    int x = a + dx[z], y = b + dy[z];
                    if (x >= 0 && x <= m - 1 && y >= 0 && y <= n - 1 && !vis[x][y] && maze[x][y] == '.')
                    {
                        if (x == 0 || x == m - 1 || y == 0 || y == n - 1) return step;
                        q.push({ x,y });
                        vis[x][y] = true;
                    }
                }
            }
        }
        return -1;
    }
};